﻿using Timer = System.Threading.Timer;

namespace AntdTest.Forms
{
    public partial class Calendar : AntdUI.Window
    {
        readonly List<AntdUI.Button> btnLst = [];
        protected Timer? timer;

        public Calendar()
        {
            InitializeComponent();

            Text = $"{Globals.App.Name} - 日历";
            Size = new Size(350, 450);
            FormBorderStyle = FormBorderStyle.FixedSingle;
            Resizable = false;
            StartPosition = FormStartPosition.Manual;
            ShowInTaskbar = false;
            TopMost = true;

            Shown += Calendar_Shown;
            VisibleChanged += Calendar_VisibleChanged;
            FormClosing += Calendar_FormClosing;

            SetToday();
            SetTodayYm();
            CheckToday();

            //tipB.SetTip(labelTodaySolar, "今天（公历/阳历）");
            //tipB.SetTip(labelTodayLunar, "今天（农历/阴历）");
            tipB.SetTip(labelYm, "年月（左键单击可回到本月）");
            tipB.SetTip(btnYMinus, "上一年");
            tipB.SetTip(btnYPlus, "下一年");
            tipB.SetTip(btnYmMinus, "上一月");
            tipB.SetTip(btnYmPlus, "下一月");

            labelYm.MouseClick += new MouseEventHandler((s, e) =>
            {
                if (e.Button == MouseButtons.Left)
                {
                    string ym = $"{DateTime.Now:yyyy-MM}";
                    if (labelYm.Text != ym)
                    {
                        labelYm.Text = ym;
                        CreateCalendar();
                    }
                }
            });
            labelYm.MouseHover += new EventHandler((s, e) =>
            {
                labelYm.ForeColor = AntdUI.Style.Db.Primary;
            });
            labelYm.MouseLeave += new EventHandler((s, e) =>
            {
                labelYm.ForeColor = ForeColor;
            });

            // 上一年
            btnYMinus.Click += new EventHandler((s, e) =>
            {
                string ym = labelYm.Text!;
                DateTime dt1 = DateTime.Parse($"{ym}-01");
                DateTime dt2 = dt1.AddYears(-1);
                labelYm.Text = $"{dt2:yyyy-MM}";
                CreateCalendar();
            });
            // 下一年
            btnYPlus.Click += new EventHandler((s, e) =>
            {
                string ym = labelYm.Text!;
                DateTime dt1 = DateTime.Parse($"{ym}-01");
                DateTime dt2 = dt1.AddYears(1);
                labelYm.Text = $"{dt2:yyyy-MM}";
                CreateCalendar();
            });
            // 上一月
            btnYmMinus.Click += new EventHandler((s, e) =>
            {
                string ym = labelYm.Text!;
                DateTime dt1 = DateTime.Parse($"{ym}-01");
                DateTime dt2 = dt1.AddMonths(-1);
                labelYm.Text = $"{dt2:yyyy-MM}";
                CreateCalendar();
            });
            // 下一月
            btnYmPlus.Click += new EventHandler((s, e) =>
            {
                string ym = labelYm.Text!;
                DateTime dt1 = DateTime.Parse($"{ym}-01");
                DateTime dt2 = dt1.AddMonths(1);
                labelYm.Text = $"{dt2:yyyy-MM}";
                CreateCalendar();
            });
        }

        private void Calendar_Shown(object? sender, EventArgs e)
        {
            CreateCalendar();
        }

        private void Calendar_VisibleChanged(object? sender, EventArgs e)
        {
            if (Visible)
            {
                Helpers.Antd.InheritTheme(this);
                
                if (Globals.App.Pendants.Contains(this))
                {
                    Globals.App.Pendants.Remove(this);
                }
                Globals.App.Pendants.Add(this);
            }
            else
            {
                Globals.App.Pendants.Remove(this);
            }
        }

        private void Calendar_FormClosing(object? sender, FormClosingEventArgs e)
        {
            Hide();
            e.Cancel = true;
        }

        /// <summary>
        /// 生成日历
        /// </summary>
        private void CreateCalendar()
        {
            if (gridPanelCalendar.Controls.Count == 0)
            {
                SuspendLayout();
                // 因为在窗体显示前设置了窗体尺寸，这里需要改变一下 GridPanel 的尺寸，否则显示异常
                gridPanelYmSelect.Height = 40;
                gridPanelYmSelect.Height = 50;
            }

            #region 日历标题

            if (gridPanelCalendarTitle.Controls.Count == 0)
            {
                gridPanelCalendarTitle.SuspendLayout();
                gridPanelCalendarTitle.Controls.Add(new AntdUI.Label()
                {
                    Text = "日",
                    TextAlign = ContentAlignment.MiddleCenter,
                    BackColor = Color.Transparent,
                    Font = new(Font.FontFamily, Font.Size, FontStyle.Bold),
                });
                gridPanelCalendarTitle.Controls.Add(new AntdUI.Label()
                {
                    Text = "六",
                    TextAlign = ContentAlignment.MiddleCenter,
                    BackColor = Color.Transparent,
                    Font = new(Font.FontFamily, Font.Size, FontStyle.Bold),
                });
                gridPanelCalendarTitle.Controls.Add(new AntdUI.Label()
                {
                    Text = "五",
                    TextAlign = ContentAlignment.MiddleCenter,
                    BackColor = Color.Transparent,
                    Font = new(Font.FontFamily, Font.Size, FontStyle.Bold),
                });
                gridPanelCalendarTitle.Controls.Add(new AntdUI.Label()
                {
                    Text = "四",
                    TextAlign = ContentAlignment.MiddleCenter,
                    BackColor = Color.Transparent,
                    Font = new(Font.FontFamily, Font.Size, FontStyle.Bold),
                });
                gridPanelCalendarTitle.Controls.Add(new AntdUI.Label()
                {
                    Text = "三",
                    TextAlign = ContentAlignment.MiddleCenter,
                    BackColor = Color.Transparent,
                    Font = new(Font.FontFamily, Font.Size, FontStyle.Bold),
                });
                gridPanelCalendarTitle.Controls.Add(new AntdUI.Label()
                {
                    Text = "二",
                    TextAlign = ContentAlignment.MiddleCenter,
                    BackColor = Color.Transparent,
                    Font = new(Font.FontFamily, Font.Size, FontStyle.Bold),
                });
                gridPanelCalendarTitle.Controls.Add(new AntdUI.Label()
                {
                    Text = "一",
                    TextAlign = ContentAlignment.MiddleCenter,
                    BackColor = Color.Transparent,
                    Font = new(Font.FontFamily, Font.Size, FontStyle.Bold),
                });
                gridPanelCalendarTitle.ResumeLayout(true);
            }
            
            #endregion

            string ym = labelYm.Text!;
            int y = DateTime.Parse($"{ym}-01").Year;
            int m = DateTime.Parse($"{ym}-01").Month;
            int wd = DateTime.Parse($"{ym}-01").DayOfWeek == DayOfWeek.Sunday ? 7 : (int)DateTime.Parse($"{ym}-01").DayOfWeek;
            DateTime dtFst = DateTime.Parse($"{ym}-01").AddDays(-wd + 1);
            for (int i = 0; i < 42; i++)
            {
                DateTime dt = dtFst.AddDays(i);
                AntdUI.Button btn;
                if (gridPanelCalendar.Controls.Count == 0 ) btn = new() { Name = $"btn{i}" };
                else btn = btnLst[i];
                btn.Text = $"{dt.Day}";
                tipB.SetTip(btn, $"{dt:yyyy-MM-dd}");
                if (dt == DateTime.Now.Date)
                {
                    btn.Type = AntdUI.TTypeMini.Primary;
                    btn.ForeColor = ForeColor;
                }
                else if (dt.Year * 100 + dt.Month == y * 100 + m)
                {
                    btn.Type = AntdUI.TTypeMini.Info;
                    btn.ForeColor = ForeColor;
                }
                else
                {
                    btn.Type = AntdUI.TTypeMini.Default;
                    btn.ForeColor = Color.Gray;
                }
                if (gridPanelCalendar.Controls.Count == 0) btnLst.Add(btn);
            }
            
            if (gridPanelCalendar.Controls.Count == 0)
            {
                gridPanelCalendar.SuspendLayout();
                for (int i = 41; i > -1; i--)
                {
                    gridPanelCalendar.Controls.Add(btnLst[i]);
                }
                gridPanelCalendar.ResumeLayout(true);
                ResumeLayout(true);
            }
        }

        /// <summary>
        /// 设置今天日期
        /// </summary>
        private void SetToday()
        {
            labelTodaySolar.Text = $"{DateTime.Now:yyyy年M月d日 dddd}";
            labelTodayLunar.Text = $"农历（开发中...）";
        }

        /// <summary>
        /// 设置今天年月
        /// </summary>
        private void SetTodayYm()
        {
            labelYm.Text = $"{DateTime.Now:yyyy-MM}";
        }

        /// <summary>
        /// 每天零点检查今天日期
        /// </summary>
        private void CheckToday()
        {
            DateTime checkTime = DateTime.Today.AddDays(1).Date;
            Globals.Logger.Print($"checkTime: {checkTime}");
            TimeSpan timeUntil = checkTime - DateTime.Now;
            timer = new((_) =>
            {
                if (Visible)
                {
                    if (labelTodaySolar.Text != $"{DateTime.Now:yyyy年M月d日 dddd}")
                    {
                        SetToday();
                    }
                    if (labelYm.Text != $"{DateTime.Now:yyyy-MM}")
                    {
                        SetTodayYm();
                        CreateCalendar();
                    }
                    CheckToday();
                }
            }, null, (int)timeUntil.TotalMilliseconds, Timeout.Infinite);
        }
    }
}